package compile {
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	import compile.fonts.AFont;
	import compile.library.ILibrary;
	
	import product.Product;		

	[ SWF( backgroundColor="0xFFFFFF", frameRate="31", width="500", height="400") ]
	public class Main extends Sprite{
	
		public function Main(){
			super();
			addEventListener(Event.ADDED_TO_STAGE,_init,false,0,true);
		}
		
		private function _init(e:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE,_init,false);
			Product.register(this);

			var lib:Loader = new Loader();
			lib.contentLoaderInfo.addEventListener(Event.COMPLETE, _showLogo, false, 0, true);
			lib.load(new URLRequest("./Library.swf"),new LoaderContext(true, ApplicationDomain.currentDomain));
			
			var font:Loader = new Loader();
			font.contentLoaderInfo.addEventListener(Event.COMPLETE, _showText, false, 0, true);
			font.load(new URLRequest("./DefaultFont.swf"),new LoaderContext(true, ApplicationDomain.currentDomain));
		}
		
		private function _showText(e:Event) : void {
			try{
				var fontClass : Class = (e .currentTarget as LoaderInfo).applicationDomain.getDefinition("compile.fonts.DefaultFont") as Class; 
				var font : AFont = new fontClass();
				font.register();
				
				var txf:TextField = new TextField();
				txf.embedFonts = true;
				txf.multiline = true;
				txf.wordWrap = true;
				txf.defaultTextFormat = new TextFormat(font.fontName,12,0x0ff000);
				txf.text = "Turkish Sweater";
				txf.appendText("\n");
				if(BUILD::debug)
					txf.appendText("-> Debug ANT build!");
				else
					txf.appendText("-> ANT build!");
					
				_positionIt(txf);
				
				addChild(txf);
			}catch(err : Error){ 
				trace(err.message); 
			}
		}
		
		private function _positionIt(target : DisplayObject) : void {
			if(numChildren>0){
				var child : DisplayObject = getChildAt(0);
				target.x = child.x;
				target.y = child.y+child.height;
			}
		}

		private function _showLogo(e:Event) : void {
			try{
				var libClass : Class = (e .currentTarget as LoaderInfo).applicationDomain.getDefinition("compile.library.Library") as Class; 
				var lib : ILibrary = new libClass();
				var logo:Bitmap = lib.getAssetByName("logo") as Bitmap;
				if(logo!=null){
					_positionIt(logo);
					addChild(logo);
				}
			}catch(err : Error){ 
				trace(err.message); 
			}
		}
	}
}